layui.use([
	"layer",
	'jquery',
	'laytpl',
	'form',
	'laydate',
	'element',
	'exutil',
	'extable',
	'exconfig',
	"echarts",
	"echartsTheme",
	'eplcBizQuarterlyType',
], function () {

	var $ = layui.$;
	var layer = layui.layer;
	var form = layui.form;
	var laytpl = layui.laytpl;
	var laydate = layui.laydate;
	var element = layui.element;
	var exutil = layui.exutil;
	var extable = layui.extable;
	var exconfig = layui.exconfig;
	var echarts = layui.echarts;
	var echartsTheme = layui.echartsTheme;
	var eplcBizQuarterlyType = layui.eplcBizQuarterlyType;

	//公共
	var tab = {
		init: function () {
			//点击tab
			$('#tab').on('click', 'li', function () {
				var id = $(this).attr('id')
				$(`#${id}-content`).show().siblings().hide()
				switch (id) {
					case 'org-tab':
						break;
					case 'project-tab':
						chartByProject.getEchartData()//图表必须显示再渲染
						break;
					case 'detail-tab':
						table.init()
						break;
				}
			})
			this.initRateAllQuarterly()

			chartByOrg.init()
			chartByProject.init()
		},
		// 初始化所有评价季度
		initRateAllQuarterly: function () {
			var that = this;
			eplcBizQuarterlyType.getAllQuarterlyTypes().then(function (res) {
				var html = "";
				for (var i = 0; res.length > i; i++) {
					let selected = i == 0 ? "selected" : "";
					html +=
						'<option value="' +
						res[i].quarterlyType +
						'" ' +
						selected +
						">" +
						res[i].quarterlyType +
						"</option>";
				}
				$("#quarterlyAllTypeByOrg").html(html);
				$("#quarterlyAllTypeByProject").html(html);
				$("#quarterlyAllTypeByDetail").html(html);
				form.render("select");
				chartByOrg.getEchartData()
			});
		},
	}

	// 按科室
	var chartByOrg = {
		tag: 'org',
		chartsObj: {},//非固定
		tplChartBox: document.getElementById('tplChartBox').innerHTML,
		init: function () {
			var that = this
			//图表的搜索按钮
			$(`#${that.tag}SearchBtn`).on("click", function () {
				that.getEchartData();
			});
		},
		// 获取图表数据
		getEchartData: function () {
			var that = this;
			var obj = {
				data: {
					keyOne: $('#orgTypeByOrg').val(),//部门类型
					keyTwo: 1,//顶部tab
					quarterlyType: $("#quarterlyAllTypeByOrg").val(),
				},
			};
			eplcBizQuarterlyType.getRatingBoard(obj).then(function (res) {
				laytpl(that.tplChartBox).render(res, function (str) {
					document.getElementById('orgMain').innerHTML = str;
				});
				for (var i = 0; res.length > i; i++) {
					that.renderEchart("chart" + i, res[i].scores);
				}
			});
		},
		//渲染图表 Key：chartsObj对象的key，值为id，list：图表数据
		renderEchart(key, list) {
			var that = this;
			var yAxis = [];
			var series = [];
			list.map((v) => {
				yAxis.push(v.name);
				series.push(v.score);
			});
			var option = {
				grid: {
					top: "1%",
					left: "3%",
					right: "6%",
					bottom: "3%",
					containLabel: true,
				},
				xAxis: {
					type: "category",
					data: yAxis,
					interval: 20,
				},
				yAxis: {
					type: "value",
					splitLine: {
						show: false, // 设置为 false 以隐藏 Y 轴网格线
					},
				},
				series: [
					{
						name: "2011",
						type: "bar",
						data: series,
					},
				],
			};
			echartsTheme.valueAxis = {};
			// 由于自定义，必须每次移除
			that.chartsObj[key] = echarts.init(document.getElementById(key), echartsTheme);
			// if (!that.chartsObj[key]) {
			// 	that.chartsObj[key] = echarts.init(document.getElementById(key), echartsTheme);
			// }
			that.chartsObj[key].clear();
			that.chartsObj[key].setOption(option);

			$(window).on("resize", function () {
				that.chartsObj[key].resize();
			});
		},
	}
	// 按评价项目
	var chartByProject = {
		tag: 'project',
		chartsObj: {//固定
			comprehensiveChart: null,
			workDataChart: null,
			businessDataChart: null,
			dutyDataChart: null,
			efficiencyDataChart: null,
			answerDataChart: null,
		},
		init: function () {
			var that = this
			//图表的搜索按钮
			$(`#${that.tag}SearchBtn`).on("click", function () {
				that.getEchartData();
			});
		},
		// 获取图表数据
		getEchartData: function () {
			var that = this;
			var obj = {
				data: {
					keyOne: $('#orgTypeByProject').val(),//部门类型
					keyTwo: 2,//顶部tab
					quarterlyType: $("#quarterlyAllTypeByProject").val(),
				},
			};
			eplcBizQuarterlyType.getRatingBoard(obj).then(function (res) {
				that.renderEchart("comprehensiveChart", res.comprehensiveEva, "comprehensiveNum");
				that.renderEchart("workDataChart", res.workEva, "workNum");
				that.renderEchart("businessDataChart", res.businessEva, "businessNum");
				that.renderEchart("dutyDataChart", res.dutyEva, "dutyNum");
				that.renderEchart("efficiencyDataChart", res.efficiencyEva, "efficiencyNum");
				that.renderEchart("answerDataChart", res.answerEva, "answerNum");
			});
		},
		//渲染图表 Key：chartsObj对象的key，值为id，list：图表数据，numKey:图表数据的key
		renderEchart(key, list, numKey) {
			var that = this;
			var yAxis = [];
			var series = [];
			list.map((v) => {
				yAxis.push(v.evaluationUnit);
				series.push(v[numKey]);
			});
			var option = {
				grid: {
					top: "1%",
					left: "3%",
					right: "6%",
					bottom: "3%",
					containLabel: true,
				},
				xAxis: {
					type: "value",
					splitLine: {
						show: false, // 设置为 false 以隐藏 Y 轴网格线
					},
				},
				yAxis: {
					type: "category",
					data: yAxis,
					interval: 20,
				},
				series: [
					{
						name: "2011",
						type: "bar",
						data: series,
					},
				],
			};
			echartsTheme.valueAxis = {};
			if (!that.chartsObj[key]) {
				that.chartsObj[key] = echarts.init(document.getElementById(key), echartsTheme);
			}
			that.chartsObj[key].clear();
			that.chartsObj[key].setOption(option);

			$(window).on("resize", function () {
				that.chartsObj[key].resize();
			});
		},
	}

	// 明细
	var table = {
		tag: 'table',
		tableCurrentPage: 1,
		//初始化
		init: function () {
			var that = this
			// this.initDate();
			//渲染
			// this.renderTable();
			this.getData();
			console.log(`submit(${this.tag}SearchBtn)`)
			//搜索按钮
			form.on(`submit(${this.tag}SearchBtn)`, function (data) {
				// exutil.updateTabTable(that.tag, null, 1, data.field);
				that.getData()
				return false;
			});
			//表格：工具栏
			extable.on(`toolbar(${this.tag})`, function (obj) {
				switch (obj.event) {
					case 'export':
						that.export();
						break;
				}
				return false;
			})
			//表格：操作列
			extable.on(`tool(${this.tag})`, function (obj) {
				var data = obj.data;
				var layEvent = obj.event;
				if (layEvent == "view") {
					var url = `/modules/app/pages/eXinSheng/flow/detail/detail.html?appCode=${data.wfAppCode}&procId=${data.wfProcID}&status=3&showLike=1`;
					console.log(data, url)
					exutil.openNewPage(url);
				}
			});
			//表格：点击标题跳转详情
			$(`body`).on('click','.item-link',function(){
				//根据需要调整lay-event="view"
				$(this).closest('td').siblings().last().find('a[lay-event="view"]').click()
			})
			/* 刷新表格 使用
				exutil.toast("操作成功", null, function () {
					window.opener.updateTable();
					window.close();
				});

				兼容写法，缺点：不可用this.tag,需要将写死
				indow.updateTable = this.updateTable
			*/
			window.updateTable = ()=>{
				exutil.updateTabTable(this.tag);
			}
		},
		//初始化：时间方法
		initDate: function () {
			laydate.render({
				elem: '#date',
				type: 'datetime',
				range: true,
				ready: function (date) {
					$(".layui-laydate-footer [lay-type='datetime'].laydate-btns-time").click();
					$(".laydate-main-list-1 .layui-laydate-content li ol li:last-child").click();
					$(".layui-laydate-footer [lay-type='date'].laydate-btns-time").click();
				},
				done: function (value, date, endDate) {
					if (value == '') {
						$('#endDate').val('')
						$('#startDate').val('')
					}
					else {
						value = value.split(' - ')
						$('#startDate').val(value[0])
						$('#endDate').val(value[1])
					}
				},
				
			});
		},
		getData:function(){
			var that = this;
			var obj = {
				data: {
					keyOne: $('#orgTypeByDetail').val(),//部门类型
					keyTwo: 3,//顶部tab
					quarterlyType: $("#quarterlyAllTypeByDetail").val(),
				},
			};
			eplcBizQuarterlyType.getRatingBoard(obj).then(function (res) {
				$('#peopleNum').html(res.peopleNum || 0)
				$('#averageScore').html(res.averageScore || 0)
				$('#max').html(res.max || 0)
				$('#min').html(res.min || 0)
				that.renderTable(res.evaluationList)
			});
		},
		//渲染表格
		renderTable: function (data) {
			data = data || []
			extable.render({
				elem: "#" + this.tag,
				// url: "/api/eplc/biz/quarterlyEvaluation/getRatingBoard",
				data:data,
				// height: 'auto',
				id: this.tag,
				page: true,
				loading: true,
				toolbar: "#toolbar",
				// where: {
				// 	keyOne: $('#orgTypeByDetail').val(),//部门类型
				// 	keyTwo: 3,//顶部tab
				// 	quarterlyType: $("#quarterlyAllTypeByDetail").val(),
				// },
				defaultToolbar: ["filter"],
				cols: [
					[
						// {
						// 	type: "numbers",
						// 	width: 65,
						// 	title: "序号",
						// },
						{
							field: "ip",
							title: "日期",
							width: 150,
							templet:function(d){
								return d.createTime?d.createTime.slice(5,10):''
							}
						},
						{
							field: "appUserName",
							title: "评价人",
							width: 150,
						},
						{
							field: "evaluationUnit",
							title: "评价对象",
							minWidth: 250,
							// templet:function(d){
							// 	return `<div class="item-link">${d.title}<div>`
							// }
						},
						{ field: "averageScore", title: "综合评分", width: 170 },
						// { field: "url", title: "访问地址", width: 250 },

						// {
						// 	field: "isVote",
						// 	title: "是否投票",
						// 	width: 90,
						// 	templet: function (d) {
						// 		var txt = "待提交";
						// 		switch (d.isVote) {
						// 			case 1: {
						// 				txt = "已提交";
						// 				break;
						// 			}
						// 		}
						// 		return txt;
						// 	},
						// },
						// {
						// 	title: "操作",
						// 	toolbar: "#rowbar",
						// 	width: 130,
						// 	fixed: "right",
						// 	align: "center",
						// },
					],
				],
				exdone: function (res, curr, count) {
					// 设置当前页码
					this.tableCurrentPage = curr;
				},
			});
		},
		//导出
		export: function () {
			var data = form.val('filterForm');
			data.token = exutil.getCookie(exconfig.tokenKey);
			data = $.param(data);
			var url = exconfig.baseUrl() + '/api/info/news/flow/exportExcel?' + data
			window.open(url);
			// window.open(encodeURI(url));
		}
	};

	tab.init()
});
